package com.team.auth.service;

import com.team.system.api.domain.SysRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.team.common.core.constant.CacheConstants;
import com.team.common.core.constant.Constants;
import com.team.common.core.constant.SecurityConstants;
import com.team.common.core.constant.UserConstants;
import com.team.common.core.domain.R;
import com.team.common.core.enums.UserStatus;
import com.team.common.core.exception.ServiceException;
import com.team.common.core.text.Convert;
import com.team.common.core.utils.DateUtils;
import com.team.common.core.utils.StringUtils;
import com.team.common.core.utils.ip.IpUtils;
import com.team.common.redis.service.RedisService;
import com.team.common.security.utils.SecurityUtils;
import com.team.system.api.RemoteUserService;
import com.team.system.api.domain.SysUser;
import com.team.system.api.model.LoginUser;

import java.util.Arrays;
import java.util.List;

/**
 * 登录校验方法
 * 
 * @author ruoyi
 */
@Component
public class SysLoginService
{
    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    /**
     * 登录
     */
    public LoginUser login(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        passwordService.validate(user, password);
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        recordLoginInfo(user.getUserId());
        return userInfo;
    }

    /**
     * 手机号登录
     */
    public LoginUser loginByPhone(String phone, String code){
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(phone, code))
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "手机号/验证码必须填写");
            throw new ServiceException("手机号/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (code.length() != UserConstants.CAPTCHA_MIN_LENGTH)
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("验证码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (phone.length() != 11)
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("手机号错误");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 比对手机号和验证码
        passwordService.validatePhoneAndCode(phone, code);

        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfoByPhone(phone, SecurityConstants.INNER);

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }
        // 如果code==501，表示手机号未注册
        if (501 == userResult.getCode()){
            // 自动注册账号
            SysUser sysUser = new SysUser();
            sysUser.setPhonenumber(phone);
            // 生成一个有我们系统特征的'唯一'用户名
            String username = "user_" + System.currentTimeMillis();
            sysUser.setUserName(username);
            sysUser.setNickName("新用户_" + System.currentTimeMillis());
            sysUser.setAvatar("http://127.0.0.1:9300/statics/2025/07/10/1638860271747163886027116_20250710192153A001.jpg");
            sysUser.setRoleIds(new Long[]{101L});
            sysUser.setPwdUpdateDate(DateUtils.getNowDate());
            R<?> result = remoteUserService.registerByPhone(sysUser, SecurityConstants.INNER);
            if (R.FAIL == result.getCode())
            {
                throw new ServiceException(result.getMsg());
            }
            // 重新查询用户信息
            userResult = remoteUserService.getUserInfoByPhone(phone, SecurityConstants.INNER);
            if (R.FAIL == userResult.getCode())
            {
                throw new ServiceException(userResult.getMsg());
            }
            return userResult.getData();
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已停用");
        }
        // 这里可以添加手机号登录的特定逻辑，验证手机号角色
        List<SysRole> roles = user.getRoles();
        // 处理roles为null的情况
        if (roles == null || roles.isEmpty()) {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "用户没有角色信息");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 没有角色信息");
        }
        // 检查是否包含普通用户角色common_user
        if (roles.stream().noneMatch(role -> "common_user".equals(role.getRoleKey()))) {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "用户不是普通用户角色");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 不是普通用户角色");
        }
        recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, "登录成功");
        recordLoginInfo(user.getUserId());
        return userInfo;
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        // 更新用户登录IP
        sysUser.setLoginIp(IpUtils.getIpAddr());
        // 更新用户登录时间
        sysUser.setLoginDate(DateUtils.getNowDate());
        remoteUserService.recordUserLogin(sysUser, SecurityConstants.INNER);
    }

    public void logout(String loginName)
    {
        recordLogService.recordLogininfor(loginName, Constants.LOGOUT, "退出成功");
    }

    /**
     * 注册
     */
    public void register(String username, String password)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPwdUpdateDate(DateUtils.getNowDate());
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<?> registerResult = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");
    }

    public LoginUser loginByMerchant(String phone, String code) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(phone, code))
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "手机号/验证码必须填写");
            throw new ServiceException("手机号/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (code.length() != UserConstants.CAPTCHA_MIN_LENGTH)
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("验证码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (phone.length() != 11)
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("手机号错误");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(phone, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 比对手机号和验证码
        passwordService.validatePhoneAndCode(phone, code);

        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfoByPhone(phone, SecurityConstants.INNER);

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }
        // 如果code==501，表示手机号未注册
        if (501 == userResult.getCode()){
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已停用");
        }
        // 这里可以添加商家登录的特定逻辑，验证商家角色
        List<SysRole> roles = user.getRoles();
        // 处理roles为null的情况
        if (roles == null || roles.isEmpty()) {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "用户没有角色信息");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 没有角色信息");
        }
        // 检查是否包含商家角色business
        if (roles.stream().noneMatch(role -> "business".equals(role.getRoleKey()))) {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "用户不是商家角色");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 不是商家角色");
        }
        recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, "登录成功");
        recordLoginInfo(user.getUserId());
        return userInfo;
    }
}
